"""
自定义分页组件
使用说明：
在视图函数中：
    def xx_list(request):
        # 1、筛选数据
        queryset = PrettyNum.objects.all()
        # 2、实例化分页对象
        page_obj = Pagination(request, num_val)
        # 3、
        context = {
        'num_data': page_obj.page_queryset,  # 分好页的数据
        'search_data': search_data,
        'page_str_lst': page_obj.html()  # 生成页码
                }
        # 4、
        return render(request.'xx.html',context)
在html页面中：
        <ul class="pagination">
            {{ page_str_lst }}
        </ul>

"""
from django.utils.safestring import mark_safe


class Pagination(object):
    def __init__(self, request, queryset, page_size=10, page_param="page", plus=5):
        """
        :param request: 请求的对象
        :param queryset: 符合条件的数据（根据数据进行分页处理）
        :param page_size: 每页显示多少条数据
        :param page_param: 在url中传递的分页的参数(num/list/?page=12)
        :param plus: 显示当前页的前或后几页
        """

        import copy
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        page = request.GET.get(page_param, "1")

        if page.isdecimal():
            page = int(page)
        else:
            page = 1
        self.page = page
        self.page_param = page_param
        self.page_size = page_size
        self.start = (self.page - 1) * self.page_size
        self.end = self.page * self.page_size
        self.page_queryset = queryset[self.start:self.end]
        total_count = queryset.count()
        total_page_count, div = divmod(total_count, page_size)
        if div:
            total_page_count += 1
        self.total_page_count = total_page_count
        self.plus = plus

    def html(self):
        page_str_lst = []
        if self.total_page_count <= 11:
            start_page = 1
            end_page = self.total_page_count
        else:
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus
            else:
                if self.page >= self.total_page_count - 5:
                    start_page = self.page - self.plus
                    end_page = self.total_page_count

                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus

        self.query_dict.setlist(self.page_param, [1])
        page_str_lst.append('<li><a href="?{}">首页</a></li>'.format(self.query_dict.urlencode()))
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())

        else:
            self.query_dict.setlist(self.page_param, [1])
            prev = '<li><a href="?{}">上一页</a></li>'.format(self.query_dict.urlencode())
        page_str_lst.append(prev)
        for i in range(start_page, end_page + 1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = '<li class="active"><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            else:
                ele = '<li><a href="?{}">{}</a></li>'.format(self.query_dict.urlencode(), i)
            page_str_lst.append(ele)
        if self.page < self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page + 1])
            next_page = '<li><a href="?{}">下一页</a></li>'.format(self.query_dict.urlencode()
                                                                          )
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            next_page = '<li><a href="?{}">下一页</a></li>'.format(
                self.query_dict.urlencode()
            )
        page_str_lst.append(next_page)
        search_string = """
                    <li>
                        <form style="float: left;margin-left: -1px" method="get">
                            <input name="page"
                                   style="position: relative;float:left;display: inline-block;width: 80px;border-radius: 0;"
                                   type="text" class="form-control" placeholder="页码">
                            <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
                        </form>
                    </li>
                    """
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        page_str_lst.append('<li><a href="?{}">尾页</a></li>'.format(self.query_dict.urlencode()))
        page_str_lst.append(search_string)

        page_string = mark_safe("".join(page_str_lst))
        return page_string
